import { useEffect, useState } from 'react';
import { Card, Row, Col, Statistic, DatePicker, Table, Space, Segmented } from 'antd';
import {
  DollarOutlined,
  ShoppingCartOutlined,
  UserOutlined,
  RiseOutlined,
  TableOutlined,
  BarChartOutlined,
} from '@ant-design/icons';
import { Line, Column } from '@ant-design/plots';
import useAnalyticsStore from '../store/analytics/useAnalyticsStore';
import dayjs from 'dayjs';

const { RangePicker } = DatePicker;

export default function Analytics() {
  const {
    dateRange,
    salesTrend,
    dishSales,
    memberConsumption,
    statistics,
    loading,
    setDateRange,
    initAnalytics,
  } = useAnalyticsStore();

  const [salesTrendView, setSalesTrendView] = useState('table');
  const [dishSalesView, setDishSalesView] = useState('table');
  const [memberConsumptionView, setMemberConsumptionView] = useState('table');

  useEffect(() => {
    initAnalytics();
  }, []);

  const handleDateRangeChange = (dates) => {
    if (dates && dates.length === 2) {
      setDateRange(dates);
    } else if (!dates) {
      const defaultRange = [dayjs().subtract(7, 'day'), dayjs()];
      setDateRange(defaultRange);
    }
  };

  const salesTrendColumns = [
    {
      title: '日期',
      dataIndex: 'date',
      key: 'date',
      render: (date) => dayjs(date).format('YYYY-MM-DD'),
    },
    {
      title: '销售额 (¥)',
      dataIndex: 'sales',
      key: 'sales',
      render: (sales) => (
        <span style={{ fontWeight: 500, color: '#3f8600' }}>
          ¥{sales.toFixed(2)}
        </span>
      ),
    },
    {
      title: '订单数',
      dataIndex: 'orders',
      key: 'orders',
      render: (orders) => (
        <span style={{ fontWeight: 500 }}>{orders}</span>
      ),
    },
    {
      title: '客单价 (¥)',
      key: 'avgAmount',
      render: (_, record) => (
        <span style={{ fontWeight: 500 }}>
          ¥{(record.sales / record.orders).toFixed(2)}
        </span>
      ),
    },
  ];

  const dishSalesColumns = [
    {
      title: '排名',
      key: 'rank',
      width: 80,
      render: (_, __, index) => (
        <span style={{ fontWeight: 600, fontSize: 16, color: index < 3 ? '#faad14' : '#666' }}>
          {index + 1}
        </span>
      ),
    },
    {
      title: '菜品名称',
      dataIndex: 'dishName',
      key: 'dishName',
    },
    {
      title: '销售额 (¥)',
      dataIndex: 'sales',
      key: 'sales',
      render: (sales) => (
        <span style={{ fontWeight: 500, color: '#3f8600' }}>
          ¥{sales.toFixed(2)}
        </span>
      ),
    },
    {
      title: '订单数',
      dataIndex: 'orders',
      key: 'orders',
      render: (orders) => (
        <span style={{ fontWeight: 500 }}>{orders}</span>
      ),
    },
  ];

  const memberConsumptionColumns = [
    {
      title: '会员等级',
      dataIndex: 'level',
      key: 'level',
    },
    {
      title: '消费总额 (¥)',
      dataIndex: 'amount',
      key: 'amount',
      render: (amount) => (
        <span style={{ fontWeight: 500, color: '#3f8600' }}>
          ¥{amount.toFixed(2)}
        </span>
      ),
    },
    {
      title: '会员数',
      dataIndex: 'count',
      key: 'count',
      render: (count) => (
        <span style={{ fontWeight: 500 }}>{count}</span>
      ),
    },
    {
      title: '人均消费 (¥)',
      key: 'avgAmount',
      render: (_, record) => (
        <span style={{ fontWeight: 500 }}>
          ¥{(record.amount / record.count).toFixed(2)}
        </span>
      ),
    },
  ];

  return (
    <div className="p-6">
      <Card style={{ marginBottom: 24 }}>
        <Space size={16} align="center">
          <span style={{ fontSize: 16, fontWeight: 500 }}>选择时间范围:</span>
          <RangePicker
            value={dateRange}
            onChange={handleDateRangeChange}
            format="YYYY-MM-DD"
            size="large"
            style={{ width: 300 }}
          />
        </Space>
      </Card>

      <Row gutter={16} className="mb-6">
        <Col span={6}>
          <Card>
            <Statistic
              title="总销售额"
              value={statistics.totalSales}
              precision={2}
              prefix="¥"
              valueStyle={{ color: '#3f8600' }}
              suffix={<DollarOutlined />}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="总订单数"
              value={statistics.totalOrders}
              suffix={<ShoppingCartOutlined />}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="平均客单价"
              value={statistics.avgOrderAmount}
              precision={2}
              prefix="¥"
              suffix={<RiseOutlined />}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="活跃会员数"
              value={statistics.totalMembers}
              suffix={<UserOutlined />}
            />
          </Card>
        </Col>
      </Row>

      <Row gutter={16} className="mb-6">
        <Col span={24}>
          <Card 
            title="销售趋势"
            extra={
              <Segmented
                value={salesTrendView}
                onChange={setSalesTrendView}
                options={[
                  { label: '表格', value: 'table', icon: <TableOutlined /> },
                  { label: '图表', value: 'chart', icon: <BarChartOutlined /> },
                ]}
              />
            }
          >
            {salesTrendView === 'table' ? (
              <Table
                dataSource={salesTrend}
                columns={salesTrendColumns}
                rowKey="date"
                loading={loading}
                pagination={{
                  pageSize: 10,
                  showTotal: (total) => `共 ${total} 天`,
                }}
              />
            ) : (
              <Line
                data={salesTrend.map(item => ({
                  date: dayjs(item.date).format('MM-DD'),
                  sales: item.sales
                }))}
                xField="date"
                yField="sales"
                height={400}
                style={{
                  lineWidth: 2
                }}
                point={{
                  size: 5,
                  shape: 'circle',
                }}
              />
            )}
          </Card>
        </Col>
      </Row>

      <Row gutter={16}>
        <Col span={12}>
          <Card 
            title="菜品销量排行 TOP 5"
            extra={
              <Segmented
                value={dishSalesView}
                onChange={setDishSalesView}
                options={[
                  { label: '表格', value: 'table', icon: <TableOutlined /> },
                  { label: '图表', value: 'chart', icon: <BarChartOutlined /> },
                ]}
              />
            }
          >
            {dishSalesView === 'table' ? (
              <Table
                dataSource={dishSales}
                columns={dishSalesColumns}
                rowKey="dishName"
                pagination={false}
              />
            ) : (
              <Column
                data={dishSales.map((item, index) => ({
                  ...item,
                  index
                }))}
                xField="dishName"
                yField="orders"
                height={400}
                style={{
                  maxWidth: 40,
                  fill: ({ index }) => {
                    const colors = ['#faad14', '#ff7a45', '#1890ff', '#52c41a', '#722ed1'];
                    return colors[index] || '#1890ff';
                  }
                }}
              />
            )}
          </Card>
        </Col>
        <Col span={12}>
          <Card 
            title="会员消费分布"
            extra={
              <Segmented
                value={memberConsumptionView}
                onChange={setMemberConsumptionView}
                options={[
                  { label: '表格', value: 'table', icon: <TableOutlined /> },
                  { label: '图表', value: 'chart', icon: <BarChartOutlined /> },
                ]}
              />
            }
          >
            {memberConsumptionView === 'table' ? (
              <Table
                dataSource={memberConsumption}
                columns={memberConsumptionColumns}
                rowKey="level"
                pagination={false}
              />
            ) : (
              <Column
                data={memberConsumption.map((item, index) => ({
                  level: item.level,
                  avgAmount: parseFloat((item.amount / item.count).toFixed(2)),
                  count: item.count,
                  index
                }))}
                xField="level"
                yField="avgAmount"
                height={400}
                style={{
                  maxWidth: 40,
                  fill: ({ index }) => {
                    const colors = ['#722ed1', '#1890ff', '#52c41a', '#faad14'];
                    return colors[index] || '#722ed1';
                  }
                }}
                tooltip={{
                  field: 'avgAmount',
                  formatter: (datum) => ({
                    name: '人均消费',
                    value: `¥${datum.avgAmount.toFixed(2)}`
                  })
                }}
              />
            )}
          </Card>
        </Col>
      </Row>
    </div>
  );
}
